<template>
    <el-dialog
    :title="title"
    width="60%"
    top='2vh'
    :visible.sync="show"
    :before-close="close"
    :close-on-click-modal="false"
    append-to-body>
    <el-form :model="contractFileSigner" ref="contractFileSignerRef">
    <div class="flex-row">
      <div>
         <el-card class="box-card">
         <div slot="header">
            <span class="card-header">公司：{{contractInfo.companyName}}</span>
         </div>
        <div  class="cpSigner" v-for="(item,index) in contractFileSigner.companyContractSignerInfoList" :key="'cpSigner-'+index">
            <el-form-item
              v-show="false"
               :prop="'companyContractSignerInfoList.'+index+'.id'">
                <el-input v-model="item.id" placeholder=""></el-input>
            </el-form-item>
          <el-form-item
            :label="'签署人'+(index+1)"
            :prop="'companyContractSignerInfoList.'+index+'.signerCode'"
            :rules="{required: true, message: '签署人不能为空', trigger: 'blur'}"
             >
            <PopoverSearch
                :params="{companyCode:contractInfo.companyCode}" popoverTrigger="manual" clearable width="120px" valueKey="employeeCode"  lableKey="employeeName" type="employee" placeholder="+添加签署人" v-model="item.signerCode"
                :name.sync="item.signerName"/>
          </el-form-item>
        </div>
         <div class="flex-row card-item" v-for="(item,index) in companyObjList" :key="index">
             <div class="lable">{{item.label}}</div><div class="desc">{{item.value||'--'}}</div>
         </div>
         </el-card>
      </div>
      <div>
       <el-card class="box-card">
         <div slot="header">
            <span class="card-header">客户：{{contractInfo.customerName}}</span>
            <!-- <el-button  v-if="canModify" style="float: right; padding: 0px" @click.native="toAddSigner" type="text">添加签署人</el-button> -->
         </div>

          <div  class="ctSigner" v-for="(item,index) in contractFileSigner.contractSignerInfoList"  :key="'ctSigner-'+index">
            <el-form-item
              v-show="false"
                label="id"
               :prop="'contractSignerInfoList.'+index+'.id'">
                <el-input v-model="item.id" placeholder=""></el-input>
            </el-form-item>
          <el-form-item
            :label="'签署人'+(index+1)"
            :prop="'contractSignerInfoList.'+index+'.signerCode'"
            :rules="{required: true, message: '签署人不能为空', trigger: 'blur'}"
             >
            <PopoverSearch
                :params="{customerCode:contractInfo.customerCode}" popoverTrigger="manual" clearable width="120px" valueKey="contactsCode"  lableKey="contactsName" type="customerSigner" placeholder="+添加签署人" v-model="item.signerCode"
                :name.sync="item.signerName"/>
          </el-form-item>
          </div>
        <div class="flex-row card-item" v-for="(item,index) in customerObjList" :key="index">
             <div class="lable">{{item.label}}</div><div class="desc">{{item.value||'--'}}</div>
         </div>
        </el-card>
      </div>
    </div>
    </el-form>
    <div style="text-align:center;margin-top:5px;" v-if="canModify">
          <el-button type="" @click.native="close">取 消</el-button>
          <el-button type="success" @click.native="save">确 定</el-button>
    </div>
    </el-dialog>
</template>
<script>
import Mixins from '../mixins'
import PopoverSearch from '@/views/components/popoverSearch'
import {groupBy} from '@/utils'
export default {
  props: {
    canModify: {type: Boolean, default: true},
    visible: Boolean,
    title: String,
    data: Array,
    contractFileInfo: {type: Object,
      default: () => {
        return {}
      }}
  },
  components: {PopoverSearch},
  mixins: [Mixins],
  watch: {
    visible: {
      handler (val) {
        this.show = val
      },
      immediate: true
    },
    data: {
      handler (val) {
        if (val) {
          let [contractInfo, contractTemplateInfo] = val
          this.contractInfo = {...contractInfo}
          this.initSigner(contractTemplateInfo)
          this.getCompanyInfo(contractInfo.companyCode)
          this.getCustomerInfo(contractInfo.customerCode)
        }
      },
      deep: true,
      immediate: true
    },
    show (val) {
      this.$emit('update:visible', val)
    }
  },
  data () {
    return {
      show: false,
      contractInfo: {},
      companyObjList: [],
      customerObjList: [],
      contractFileSigner: {
        contractSignerInfoList: [], // 客户签署人
        companyContractSignerInfoList: []// 公司签署人
      }
    }
  },
  methods: {
    close () {
      this.show = false
    },
    initSigner (contractTemplateInfo) {
      const customerSignerCount = contractTemplateInfo.customerSignerCount
      const companySignerCount = contractTemplateInfo.companySignerCount
      if ((customerSignerCount && customerSignerCount > 0) || (companySignerCount && companySignerCount > 0)) {
        this.getContractFileSignerList(this.contractFileInfo.contractFileCode).then(res => {
          if (res.code === 0) {
            const signerMap = res.data && res.data.length > 0 ? groupBy(res.data, 'signerType') : null
            const contractSignerInfoList = signerMap ? signerMap['0'] : []
            const companyContractSignerInfoList = signerMap ? signerMap['1'] : []
            this.contractFileSigner.contractSignerInfoList = this.getSingerList(contractSignerInfoList, customerSignerCount)
            this.contractFileSigner.companyContractSignerInfoList = this.getSingerList(companyContractSignerInfoList, companySignerCount)
          }
          // console.log(' this.contractFileSigner', this.contractFileSigner)
        })
      }
    },
    getSingerList (signerList, signerCount) {
      let contractSignerInfoList = []
      if (signerList && signerList.length > 0) {
        const lt = signerList.length
        contractSignerInfoList = [...signerList]
        if (signerCount !== lt && signerCount > lt) {
          contractSignerInfoList = [...contractSignerInfoList, ...this.generateSigner(signerCount - lt)]
        }
      } else {
        contractSignerInfoList = this.generateSigner(signerCount)
      }
      return contractSignerInfoList
    },
    generateSigner (count) {
      const contractSignerInfoList = []
      if (count && count > 0) {
        for (let index = 0; index < count; index++) {
          contractSignerInfoList.push({
            id: null,
            signerCode: null,
            signerName: null,
            key: new Date()
          })
        }
      }
      return contractSignerInfoList
    },
    getCompanyInfo (companyCode) {
      this.requestOption('getCompanyInfo', companyCode, (res) => {
        if (res.code === 0) {
          const companyInfo = res.data || {}
          this.companyObjList = [
            // {label: '代表签字：', value: this.contractInfo.chargePersonName},
            {label: '公司法人：', value: companyInfo.legalName},
            {label: '公司电话：', value: companyInfo.telphone},
            {label: '公司传真：', value: companyInfo.fax},
            {label: '公司税号：', value: companyInfo.taxNumber},
            {label: '开户银行号：', value: companyInfo.depositBankNo},
            {label: '开户银行：', value: companyInfo.depositBank},
            {label: '公司地址：', value: companyInfo.address}
          ]
        }
      })
    },
    getCustomerInfo (customerCode) {
      this.requestOption('getCustomerInfo', customerCode, (res) => {
        if (res.code === 0) {
          const customerInfo = res.data || {}
          this.customerObjList = [
            {label: '公司电话：', value: customerInfo.telephone},
            {label: '公司传真：', value: customerInfo.fax},
            {label: '公司邮箱：', value: customerInfo.email},
            {label: '公司地址：', value: customerInfo.address}
          ]
        }
      })
    },
    getContractFileSignerList (contractFileCode) {
      return new Promise((resolve, reject) => {
        this.requestOption('getContractFileSignerList', contractFileCode, (res) => {
          resolve(res)
        })
      })
    },
    removeSigner (item, key = 'contractSignerInfoList') {
      if (item && item.id && item.id !== '') {
        const contractFileCode = this.contractFileInfo.contractFileCode
        const signerCode = item.signerCode
        this.$msgBox.confirm('确认删除签署人', () => {
          this.requestOption('deleteContractSigner', {contractFileCode, signerCode}, (res) => {
            if (res.code === 0) {
              this.getContractFileSignerList(this.contractFileInfo.contractFileCode)
            }
          })
        })
      } else {
        var index = this.contractFileSigner[key].indexOf(item)
        if (index !== -1) {
          this.contractFileSigner[key].splice(index, 1)
        }
      }
    },
    toAddSigner (key = 'contractSignerInfoList') {
      this.contractFileSigner[key].push({
        id: null,
        signerCode: null,
        signerName: null
      })
    },
    save () {
      this.$refs.contractFileSignerRef.validate(validate => {
        if (validate) {
          this.contractFileSigner.contractFileCode = this.contractFileInfo.contractFileCode
          this.contractFileSigner.contractCode = this.contractInfo.contractCode
          if (!this.contractFileInfo.contractFileCode || !this.contractInfo.contractCode) {
            this.$msgBox.error('合同或合同文件编码不存在')
            return
          }
          this.requestOption('saveContractSigner', this.contractFileSigner, (res) => {
            if (res.code === 0) {
              this.contractFileInfo.isConfirmSinger = true
              this.contractFileInfo.isConfirmFile = false
              this.$msgBox.success('合同签署方已确认，需重新确认合同文件', () => {
                this.close()
              }, 3000)
            //   this.getContractFileSignerList(this.fileCode)
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.flex-row{
    display: flex;
    flex-direction: row;
    justify-content: space-around;
}
.box-card{
    width: 350px;
    .card-header{
        font-weight: 600;
    }
    .card-item{
        margin: 10px 0;
    }
    .lable{
        width: 100px;
        text-align: right;
    }
    .desc{
        width: 250px;
        font-size: 12px;
    }
}
</style>
